<template>
	<view class="root">
		<view class="item-container" v-if="loading">
			<!-- 标题显示 -->
			<text class="item-title">{{blog.title}}</text>
			<!-- 文章内容显示 -->
			<text class="item-author">{{blog.user.nickName}}@{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-desc"></rich-text>
			<!-- 图片显示 -->
			<image :src="blog.picture" mode="widthFix" class="item-focus"></image>
			<!-- 头像显示 -->
			<image :src="blog.user.avatar" mode="aspectFill" class="item-avatar"></image>
			<!-- 显示标签，标签就是文本 -->

			<view class="icon-container">
				<text
					:class="goodIds.indexOf(blog.id)>=0?'iconfont icon-xihuan1 ic-red':'iconfont icon-xihuan1 ic-gray' "
					@click.stop="changeGood(blog.id)"></text>
				<text class="icon-text">{{blog.good}}</text>
				<image src="/static/icons(1)/ic_comment.png" class="icon"></image>
				<text class="icon-text">{{blog.comments.length}}</text>
				<image src="/static/icons(1)/ic_count.png" class="icon"></image>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
			<text class="iconfont icon-tianranqi icon-tag" @click.stop="drop(item.id)"></text>
		</view>
		
		<view v-if="hasComment" class="item-container">
			<view v-for="(parent,index) in parents" :key="parent.id">
				<view class="cmt-container">
					<text class="cmt-author">{{parent.nickName}}</text>
					<text class="cmt-time">{{parent.createTime}}</text>
					<image :src="parent.avatar" mode="aspectFill" class="cmt-avatar"></image>
					<text class="cmt-content" @click="clickReply(parent)">{{parent.content}}</text>
				</view>
				<!-- 子评论列表 -->
				<view v-if="replies[index].length>0" class="reply-container">
				   <view v-for="(reply,idx) in replies[index]" class="reply-item" :key="reply.id">
					   <view class="reply-info">
						   <text class="reply-author">{{reply.nickName}}</text>
						   <text class="reply-to">@{{reply.toUser}}</text>
						   <text class="reply-time">{{reply.createTime}}</text>
					   </view>
					   <view class="reply-content" @click="clickReply(reply)">{{reply.content}}</view> 
				   </view>
				</view>
				<view v-if="index < parents.length -1" class="cmt-line"></view><!-- 分割线 -->
			</view>
		</view>
		
		<view class="input-container">
			<image :src="avatar" mode="aspectFill" class="input-avatar" @click.stop="showuser"></image>
			<textarea auto-height :value="inputValue" :placeholder="inputHolder" @input="inputGetArea" class="input-area" placeholder-class="input-holder"/>
			<text class="iconfont icon-icon-test2 input-commit" @click="clickCommit"></text>
		</view>
		    
		<login-dialog ref="login" @login="afterLogin"></login-dialog>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				goodIds: [],
				blog: {},
				loading: false,
				parents:[],
				replies:[],
				hasComment:false,
				avatar:'../../static/icons(1)/default_user.png',
				inputValue:'',
				inputHolder:'请输入评论内容...',
				parentId:null
			};
		},
		onLoad(options) {
					let ids=uni.getStorageSync(this.$params.key_good_ids)
						
					if(ids){
						this.goodIds=ids
					}
					let id = options.id;
					this.getBlog(id);
					this.$noti.add(this.$params.noti_login_status,this.afterLogin,this)
				},
				onUnload() {
					this.$noti.remove(this.$params.noti_login_status,this)
				},
		onUnload() {
			this.$noti.remove(this.$params.noti_login_status,this)
		},
		methods: {
			clickCommit(){
				const app = getApp();
				if(app.globalData.token.length === 0){
					this.$refs.login.show();
					return;
				}
				if(this.inputValue.length === 0){
					uni.showToast({ title: '请输入评论内容' });
					return;
				}
				const url = this.$params.host + this.$params.action_comment;
				const data = {
					nick_name: app.globalData.nickName,
					avatar: '/'+app.globalData.avatar,
					email: app.globalData.email,
					content: this.inputValue,
					blog_id: this.blog.id,
					parent_id: this.parentId,
					token: app.globalData.token,
					is_owner: app.globalData.id == this.blog.user.id
				};
				uni.showLoading({ title: '上传评论', mask: false });
				this.$req.post(url, data, res => {
					res = res.data;
					const cmt = res.data;
					let comments=this.blog.comments.concat(cmt)
					this.blog.comments=comments
					console.log(comments);
					this.formatComments(comments)
					this.hasComment=this.blog.comments.length>0
					this.inputValue=''
					this.parentId=null
					this.inputHolder='请输入评论内容'
					let pages=getCurrentPages()
					let prev=pages[pages.length-2]
					prev.refreshComments(cmt)
				}, () => {
					uni.hideLoading();
				});
			},
			clickReply(reply){
				this.parentId = reply.id;
				this.inputHolder = '@'+reply.nickName; 
			},
			inputGetArea(e){
				this.inputValue = e.detail.value
			},
			afterLogin(){
				this.avatar = this.$params.host + getApp().globalData.avatar;
			},
			showuser(){
				this.$refs.login.show();
			},
			getBlog(id) {
				const url = this.$params.host + this.$params.action_top_blogs + id;
				this.$req.get(url, (res) => {
					const blog = res.data.data;
					uni.setNavigationBarTitle({ title: blog.user.nickName });
					blog.picture = this.$params.host + blog.picture;
					blog.user.avatar = this.$params.host + blog.user.avatar;
					blog.createTime = this.$formatTime(new Date(blog.createTime));
					blog.updateTime = this.$formatTime(new Date(blog.updateTime));
					blog.content = blog.content.replace(/https/gi, 'http').replace(/\<img/gi, '<img class="rich-img"');
					this.blog = blog;
					this.formatComments(blog.comments);
					this.loading = true;
					this.addReadCount(id);
				});
			},
			addReadCount(id) {
				const url = this.$params.host + this.$params.action_read_count;
				const data = { id: id };
				this.$req.postQuery(url, data, res => {
					this.blog.readCount = res.data.data;
					this.$noti.post(this.$params.noti_refresh_count, { id, count: res.data.data });
				}, () => {});
			},
			changeGood(id) {
				const isGood = this.goodIds.indexOf(id) === -1;
				if (isGood) {
					this.goodIds.push(id);
				} else {
					this.goodIds = this.goodIds.filter(item => item !== id);
				}
				uni.setStorageSync(this.$params.key_good_ids, this.goodIds);
				this.postGood(id, isGood);
			},
			postGood(id, isGood) {
				uni.showLoading({ title: '点赞...', mask: false });
				const url = this.$params.host + (isGood ? this.$params.action_good : this.$params.action_del_good);
				const data = { id: id };
				this.$req.postQuery(url, data, res => {
					this.blog.good = res.data.data;
					this.$noti.post(this.$params.noti_change_good, { id, count: res.data.data });
					uni.hideLoading();
				}, () => {
					uni.hideLoading();
				});
			},
			formatComments(comments){
				if(comments.length === 0) return;
				const parents = [];
				comments.forEach(c => {
					if (!c.avatar?.startsWith('http')) { 
					      c.avatar = this.$params.host + (c.avatar?.startsWith('/') ? c.avatar : `/${c.avatar}`); 
					    }
					// c.avatar = this.$params.host + c.avatar.substring(1);
					c.createTime = this.$formatTime(new Date(c.createTime));
					if(c.parentId === null) parents.push(c);
				});
				parents.sort((p1, p2) => new Date(p2.createTime) - new Date(p1.createTime));
				const replies = parents.map(p => this.findAllChildren(p, comments));
				this.parents = parents;
				this.replies = replies;
				this.hasComment = comments.length > 0;
			},
			findAllChildren(parent, comments){
				const result = [];
				comments.forEach(c => {
					if(c.parentId === parent.id){
						c.toUser = parent.nickName;
						result.push(c);
						result.push(...this.findAllChildren(c, comments));
					}
				});
				return result;
			}
		}
	};
</script>

<style>
	@import url("blog.css");
</style>
